package per.chao.mqtt.domain.repo;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import per.chao.mqtt.domain.interfaces.repo.BaseRepo;
import per.chao.mqtt.domain.shared.store.SessionStore;
import per.chao.mqtt.domain.util.TaskCircle;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * Description: session存储实现
 *
 * @author W.Chao
 * @date 2021/6/20 14:23
 **/
@Component
@Slf4j
public class SessionRepo extends BaseRepo<SessionStore> {
	private Map<String, SessionStore> sessionCache = Maps.newConcurrentMap();

	@PostConstruct
	public void construct() {

		TaskCircle.addTask(new TimerTask() {
			@Override
			public void run() {
				Set<String> sessions = sessionCache.keySet();
				log.info("current sessions: {}", sessions);
			}
		}, TimeUnit.SECONDS.toMillis(1), TimeUnit.SECONDS.toMillis(10));
	}

	@Override
	public void put(String clientId, SessionStore sessionStore) {
		sessionCache.put(clientId, sessionStore);
	}

	@Override
	public SessionStore get(String clientId) {
		return sessionCache.get(clientId);
	}

	@Override
	public void remove(String clientId) {
		sessionCache.remove(clientId);
	}

	@Override
	public boolean containsKey(String clientId) {
		return sessionCache.containsKey(clientId);
	}
}
